<?php
require_once("facebook.php");

class IndexController extends Zend_Controller_Action
{
	private $user;
	private $mailQueue;
	
	public function init() {
	   	$this->user = new User();
	   	$this->mailQueue = new MailQueue();
		$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
		$this->initView();
		$this->view->flashmsgs = $this->_flashMessenger->getMessages();
	}

	public function testfbAction() {
	}
	
    public function testAction() {
//    	$facebook = new Facebook(
//    	array(  
//    	'appId'  => '123119317757269',  
//    	'secret' => '470f0874c274de341e189585dfe5c784', 
//    	'cookie' => true
//    	)
//    	);
//    	
//    	$session = $facebook->getSession(); 
////    	print_r($session);
////    	print_r($facebook);
//        $user = $facebook->getUser();
////        print_r($user);
//        
//        try {
//        	$me = $facebook->api('/me');
//        	$user_info = $facebook->api_client->users_getInfo($uid, "name, city, zipcode");
//        	print_r($user_info);
//        	
//        } catch (FacebookApiException $e) {
//        	header("Location:{$facebook->getLoginUrl(array("req_perms" => "user_status,publish_stream,user_photos"))}");
//        }
//        
////        var_dump($me);
//    	if(is_null($facebook->getUser())) {
//    		echo "not login";
//    		$login_url = $facebook->getLoginUrl();
////    		header("Location:{$facebook->getLoginUrl(array("req_perms" => "user_status,publish_stream,user_photos"))}");
//    	} else {
//    		echo "login";
//    		echo $facebook->getLogoutUrl();
////    		header("Location:{$facebook->getLogoutUrl()}");
//    	}
    	
    	echo count(User::getActiveUsers(1));
    	echo "<br/>";
    	echo count(Book::getTotalBooks(1));
    	echo "<br/>";
    	echo count(User::getActiveUsers(9));
        echo "<br/>";
        echo count(Book::getTotalBooks(9));
//    	echo $login_url;  
//    	header("Location: ".$login_url);  
    	
//    	$date = $this->_helper->generator->generateCurrentTime();
//    	//echo $date;
//    	$date = new Zend_Date();
//    	$date=$this->_helper->generator->manipulatDate($date, '10', Zend_Date::MINUTE);
//    	echo $date;
//    	
//    	$config = Zend_Registry::get('config');
//        $amazonApiKey = $config->amazon->api->key;
//        $amazonSecretKey = $config->amazon->secret->key;
//    	$amazon = new Zend_Service_Amazon($amazonApiKey, 'US', $amazonSecretKey);
//            $results = $amazon->itemSearch(array(
//            'SearchIndex'   => "Books",
//            'Keywords'      => "java",
//            'ItemPage' => 3,
//            'ResponseGroup' => 'Medium'));
//    	foreach ($results as $result) {
//    		echo $result->Title;
//    		echo "<br/>";
//    		echo $result->Amount;
//    		echo "<br/>------------<br/>";    	
//    	}
    	exit;
    }
    
    /**
     * Expire search data.
     */
    public function expiresearchdataAction() {
    	$db = Zend_Registry::get('db');
    	$db->beginTransaction();
    	$currentTime = $this->_helper->generator->generateCurrentTime();
    	$this->searchDataCache->expireSearchData($currentTime);
    	$db->commit();
    	exit;
    }
    
    public function indexAction() {
    	$config = Zend_Registry::get("config");
    	//$activityLimit = $config->activity->show->limit;
        $this->view->headScript ()->appendFile ( $config->baseurl . '/js/index.js' );
    	
    	$form = new SearchBookInSite();
    	$this->view->form = $form;
    	$this->view->pageName="home";
    	
    	if ($this->_helper->user->isLoggedIn()) {
    		$user = $this->user->findById($this->_helper->user->getUserData()->id);
    		$this->view->user = $user;
    	}
    	
    /*	$cityId = $this->_helper->user->getUserViewCity();
    	if ($this->_helper->user->isLoggedIn()) {
    		$user = $this->user->findById($this->_helper->user->getUserData()->id);
    		$activities = User::getActivityByUserCity($cityId, 15);
    		$this->view->user = $user;
    	} else {
    		//UnloggedIn 10 items
    		$activities = User::getActivityByUserCity($cityId, 10);
    	}
    	
    	//TODO sizeOf not good, it should be select count(*)
    	$this->view->totalBooks = sizeOf(Book::getTotalBooks($cityId, UserBookStatus::AVAILABLE));
    	$this->view->activities = $this->_helper->activity($activities);   		*/
    	//$this->view->topUsers = User::getTopUsers($cityId,12);
    //	$this->view->randomBooks = Book::getRandomBooks($cityId, 12);
    	
    }

    public function activitiesajaxAction(){
    	   	
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
    	$cityId = $this->_helper->user->getUserViewCity();
    	if ($this->_helper->user->isLoggedIn()) {
    		$user = $this->user->findById($this->_helper->user->getUserData()->id);
    		$activities = User::getActivityByUserCity($cityId, 15);
    	} else {
    		//UnloggedIn 10 items
    		$activities = User::getActivityByUserCity($cityId, 10);   		
    	}
    	
    	$content = $this->view->activityList($this->_helper->activity($activities),true);
    	$totalBooks = sizeOf(Book::getTotalBooks($cityId, UserBookStatus::AVAILABLE));
   //	$content = $activities;
    	
    	$returnJson = array(
          		"content" => $content,
    			"totalBooks"=>$totalBooks
        	);
        
        echo Zend_Json::encode($returnJson);   	
    }
    
    
    
    public function topusersajaxAction(){
    	   	
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
    	$cityId= $this->_helper->user->getUserViewCity();
    	$content = $this->view->userThumbnailList(User::getTopUsers($cityId,12));
    	
    	$returnJson = array(
          		"content" => $content
        	);
        
        echo Zend_Json::encode($returnJson);   	
    }
    
    public function randombooksajaxAction(){
    	   	
		$this->_helper->viewRenderer->setNoRender();   //view info disabled
		$this->_helper->getHelper('layout')->disableLayout(); //template disabled
		
    	$cityId= $this->_helper->user->getUserViewCity();
    	$content = $this->view->bookThumbnailList(Book::getRandomBooks($cityId, 12));
    	
    	$returnJson = array(
          		"content" => $content
        	);
        
        echo Zend_Json::encode($returnJson);   	
    }
       
    public function aboutAction() {
        $this->view->pageTitle=  "HeyIdleBooks | About Us";
    }
    
	public function termsAction() {
        $this->view->pageTitle=  "HeyIdleBooks | Terms";
	}
	
	/**
	 * Contact us.
	 */
    public function contactAction() {
        
        $this->view->pageTitle=  "HeyIdleBooks | Contact Us";
        $config = Zend_Registry::get('config');
        $this->view->headScript ()->appendFile ( $config->baseurl . '/js/jquery.validate.min.js' );
        $this->view->headScript ()->appendFile ( $config->baseurl . '/js/contact.js' );
        $form = new ContactUs();
        
        $this->view->form = $form;
        if ($this->getRequest ()->isPost ()) {
            if ($form->isValid ( $_POST )) {
                $captcha = $form->getValue ( 'captcha' );
                $isValid = $this->_helper->common->validateCaptcha($captcha);
                
                if ($isValid) {
                    $name = $form->getValue ( 'name' );
                    $email = $form->getValue ( 'email' );
                    $body = nl2br ( $form->getValue ( 'body' ) );
                    
                    $db = Zend_Registry::get ( 'db' );
                    $db->beginTransaction ();
                    $this->mailQueue->addToQueue ( Activity::CONTACT_US, 'Contact Us', $email, Constant::SYS_INFO_EMAIL, $body, $this->_helper->generator->generateCurrentTime () );
                    $db->commit ();
                    $this->_flashMessenger->addMessage ("Your message is sent successfully!");
                    $this->_redirect ( '/contact-us' );
                } else {
                    throw new Zend_Exception('Wrong captcha!');
                }
            }
        }
    }

    public function robotsAction() {
        $this->_helper->layout->disableLayout();
    	// Set content-type header to text/plain
    	$this->getResponse()->setHeader('Content-Type', 'text/plain');
    }

}

